import {MessageInstance} from "antd/es/message/interface";
import {ThunkDispatch} from "@reduxjs/toolkit";
import {NavigateFunction} from "react-router-dom";
import LogFactory from "../log/LogFactory";
import {AsyncThunk, AsyncThunkConfig} from "@reduxjs/toolkit/dist/createAsyncThunk";
import JsonResult from "../http/JsonResult";

const log = LogFactory.getLogger("Hyacinth");
/**
 * 全局操纵对象
 */
export default class Hyacinth{
    /** 唯一实例 */
    private static _instance: Hyacinth = new Hyacinth();
    /** 全局消息对象 */
    private message: MessageInstance | undefined;
    /** 全局redux调度对象 */
    private dispatch: ThunkDispatch<any, any, any> | undefined;
    /** 路径跳转对象 */
    private navigate: NavigateFunction | undefined;

    /** 设置全局消息对象 */
    public setMessage(message: MessageInstance){
        this.message = message;
    }

    public getMessage(): MessageInstance{
        if (!this.message){
            throw new Error("全局消息对象未设置!");
        }
        return this.message;
    }

    /** 设置全局redux调度对象 */
    public setDispatch(dispatch: ThunkDispatch<any, any, any>){
        this.dispatch = dispatch;
    }
    /**
     * 获取全局消息对象
     */
    public getDispatch(): ThunkDispatch<any, any, any> {
       if (!this.dispatch){
           throw new Error("全局消息对象未设置!");
       }
        return this.dispatch;
    }

    /**
     * 执行删除操作的异步action
     * @param asyncAction 异步action
     * @param param 执行参数
     */
    public async executeDeleteDispatch(asyncAction: AsyncThunk<JsonResult<number>, number, AsyncThunkConfig>, param: number){
       const res = await this.getDispatch()(asyncAction(param)).unwrap();
        if (res.success && res.data > 0){
            this.getMessage().success("删除成功");
        }else {
            this.getMessage().error("删除失败");
        }
    }

    /** 设置全局路由跳转对象 */
    public setNavigate(navigate: NavigateFunction){
        if(this.navigate){
            // log.debug("路由跳转对象已经存在,不允许重复设置");
            return;
        }
        this.navigate = navigate;
    }
    /** 获取全局操作对象实例 */
    public static getInstance(): Hyacinth {
        return this._instance;
    }
}